#include "stdafx.h"
#include "JSONGetPost.h"
#pragma warning(disable: 4996)

//Set following to true to do table get and to false to post a new name-value pair
// App defaults to GET
// If commandline is POST then does POST


#define BUFFSIZE 21
#define STRNSIZE (BUFFSIZE-1)

//The Default GET Query parameter:
#define DEFAULTFILTER  "embedded=1"


HTTPModeEnum gHttpMode = DOGET;

int wmain(int argc, wchar_t *argv[])
{

	char HTTPMode[BUFFSIZE];
	//The  GET Query parameter:
	char Filter[3*BUFFSIZE];
	char Sensor[BUFFSIZE];
	char PARAM2[BUFFSIZE];
	char PARAM3[BUFFSIZE];
	char PARAM4[BUFFSIZE];

	int id = 8;
	int iValue = 99;

	HTTPMode[0] = '\0';
	Filter[0] = '\0';
	Sensor[0] = '\0';
	PARAM2[0] = '\0';
	PARAM3[0] = '\0';
	PARAM4[0] = '\0';
	int numParams = 0;

	output.begin(0);
	output.Enable();

	output.print("Num parameters: ");
	output.println(argc);

	if (argc>1)
	{
		wcstombs(HTTPMode, argv[1], STRNSIZE);
		int i = 0;
		//Convert HTTPMode to uppercase
		while (HTTPMode[i])
		{
			char c = toupper(HTTPMode[i]);
			HTTPMode[i] = c;
			i++;
		}
		HTTPMode[3] = '\0';  //Except 3 letter verbs
		if (argc > 2)
		{
			wcstombs(PARAM2, argv[2], STRNSIZE);
			if (argc > 3)
			{
				wcstombs(PARAM3, argv[3], STRNSIZE);
				if (argc > 4)
				{
					wcstombs(PARAM4, argv[4], STRNSIZE);
				}
			}
		}
	}

	if (strcmp(HTTPMode, "GET") == 0)
	{
		gHttpMode = DOGET;
		if (argc > 2)
		{
			strcpy(Filter, PARAM2);
		}
		else
		{
			strcpy(Filter, DEFAULTFILTER);
		}

		output.print("=== Filter: ");
		output.print(Filter);
		output.println( "===");

	}
	else if ((strcmp(HTTPMode, "PAT") == 0) || (strcmp(HTTPMode, "PUT") == 0))
	{
		//Update record AzMS uses PATCH
		gHttpMode = DOPATCH;
		if (argc <5)
		{
			output.println("PATCH requires id, field and field value. Exiting");
			output.println("CEJSONApp {PATCH|PUT}  <id> <Field name> <int Field  value>");
			return 0;
		}
	}
	else if (strcmp(HTTPMode, "DEL") == 0)
	{
		//Delete
		gHttpMode = DODELETE;
		if (argc <3)
		{
			output.println("DELETE requires a record id. Exiting");
			output.println("CEJSONApp DELETE  <id>");
			return 0;
		}

	}
	else if (strcmp(HTTPMode, "POS") == 0)
	{
		//Doing a POST
		gHttpMode = DOPOST;
		if (argc < 4)
		{
			output.println("POST requires Sensor name and value. Exiting");
			output.println("CEJSONApp POST  <Sensor name> <int Sensor value>");
			return 0;
		}
	}
	else
	{
		output.println("CEJSONApp {GET|POST|PATCH|DELETE} {Filter} {id} {Field}/Sensor name} {Sensor/Field value}");
		output.println("CEJSONApp GET");
		output.println("CEJSONApp GET <Filter>");
		output.println("          Filter can be any valid AzMS Filter.  Some telemetry2 specific ones:");
		output.println("CEJSONApp GET embedded={1|2|3}");
		output.println("                        1 is the default");
		output.println("CEJSONApp GET sensor=<Sensor name>");
		output.println();
		output.println("CEJSONApp POST  <Sensor name> <int Sensor value>");
		output.println("CEJSONApp {PATCH|PUT}  <id> <Field name> <int Field  value>");
		output.println("CEJSONApp DELETE  <id>");
		output.println("Only first 3 characters of verbs are important.");
		output.println("    ie Can be GET POS PAT PUT or DEL");
		output.println();
		output.println("Defaulting to GET.");
		output.println();
		strcpy(HTTPMode, "GET");
	}


	//Read in the table the service and app key from config.txt
	FILE *fp;
	fp = fopen(".\\config.txt", "rt");
	char ch;
	int cntr = 0;
	wint_t  wch = 0;
	WCHAR  WCH = '\0';
	int mode = 0;
	while ((!feof(fp)) && (mode <3))
	{
		wch = fgetwc(fp);
		WCH = (WCHAR)wch;
		ch = (char)wch;
		if (WCH == '\n')  //wch==10
		{
			mode++;
			cntr = 0;
		}
		else
		{
			switch (mode)
			{
			case 0:
				TABLE[cntr] = ch;
				TABLE[cntr + 1] = '\0';
				break;
			case 1:
				AMW_SERVICE[cntr] = ch;
				AMW_SERVICE[cntr + 1] = '\0';
				break;
			case 2:
				APP_KEY[cntr] = ch;
				APP_KEY[cntr + 1] = '\0';
				break;
			}
			cntr++;
		}
	}
	fclose(fp);

	Init_AZMS(AMW_SERVICE, TABLE, APP_KEY);

	output.print("Doing ");
	output.println(HTTPMode);


	BOOL resp=true;



	switch (gHttpMode)
	{
		case DOGET:
			if (argc >2)
			{
				//Todo: If Filter is embedded=3 then need to pass Sensor to AzMS
				resp = GET_TelemetryTableFltr(TABLE, Filter, true);
			}
			else
			{
				//Not Filtered. Use default embedded=1
				resp = GET_TelemetryTable(TABLE, true);
			}
			break;
		case DOPOST:
			// Convert UNICODE sensor to char[]
			try
			{
				output.print(PARAM3);
				iValue = atoi(PARAM3);

			}
			catch (...)
			{
				//If invalid 
				output.println("Invalid sensor value. Using 137 for POST.");
				iValue = 137;

			}
			resp = POST_TelemetryValue(TABLE,PARAM2, iValue, true);
			//resp = POST_TelemetryValueFlt(TABLE, PARAM2,(float) iValue, true);
			break;
		case DOPATCH:
			try
			{
				iValue = atoi(PARAM4);

			}
			catch (...)
			{
				//If invalid 
				output.println("Invalid sensor value. Exiting.");
			}
			try
			{
				id = atoi(PARAM2);
			}
			catch (...)
			{
				//If invalid 
				output.println("Invalid id value. Exiting.");
			}
			if (id < 0)
			{
				//If invalid 
				output.println("Invalid id value. Exiting.");
				return 0;
			}
			output.print("Updating(Patching) record #:");
			output.print(id);
			output.print(" ");
			output.print(PARAM3);
			output.print("=");
			output.print(iValue);
			output.println();
			resp = PATCH_TelemetryRecord(TABLE, id, PARAM3 , iValue, true);
			break;
		case DODELETE:
			try
			{
				id = atoi(PARAM2);
			}
			catch (...)
			{
				//If invalid 
				output.println("Invalid id value. Exiting.");
				return 0;
			}
			if (id < 0)
			{
				//If invalid 
				output.println("Invalid id value. Exiting.");
				return 0;
			}
			output.print("Deleting record #:");
			output.println(id);
			output.println();
			resp = DELETE_TelemetryRecord(TABLE, id, true);
			break;
	}
	

	if ( 
			((!TEST) && (gHttpMode==DOGET))
					||
			(gHttpMode==DOPOST)
					||
			(gHttpMode==DODELETE)
					||
			(gHttpMode == DOPATCH)
		) //Test doesn't do the GET but feeds a sample JSON string AND parses it in GET_TelemetryTable() ..Parsing is done
	{
		if (resp)
		{
			if (gHttpMode != DODELETE) 
				InitNameValues();
			if (resp = GetResponse(gHttpMode, true))
			{
				if (gHttpMode != DODELETE) 
				{
					PrintArray();
					if (gHttpMode == DOGET) 
					{
						//Got whole table
						//Show only the most recent value for each sensor/
						CheckArray();  //Ids of other records are set to -1
						PrintArray();
					}
				}
			}
			if (gHttpMode != DODELETE) 
				DeallocateNameValues();
		}
	}
	if (resp)
		output.println("Done");
	else
		output.println("Failed");

	

	return 0;
}

